from flask import Flask, render_template, request, redirect, url_for, jsonify
from models import db, Note
from note_file_manager import load_note_from_file, save_note_to_file, update_database_from_files
import os

app = Flask(__name__)
app.config.from_object('config.Config')
db.init_app(app)

with app.app_context():
    db.create_all()
    update_database_from_files()

@app.route('/')
def index():
    selected_tags = request.args.getlist('tags')
    notes = Note.query.all()
    tags = sorted(set(tag for note in notes for tag in note.tags.split(',')))
    if selected_tags:
        notes = [note for note in notes if all(tag in note.tags.split(',') for tag in selected_tags)]
    note_list = [
        {"id": note.id, "title": note.filename, "content": load_note_from_file(note.filename)[2], "tags": note.tags}
        for note in notes
    ]
    return render_template('index.html', notes=note_list, tags=tags, selected_tags=selected_tags)

@app.route('/create', methods=['POST'])
def create_note():
    note_title = request.form['title']
    note_content = request.form['content']
    tags = request.form['tags']
    filename = save_note_to_file(note_title, note_content, tags)
    new_note = Note(filename=filename, tags=tags)
    db.session.add(new_note)
    db.session.commit()
    return redirect(url_for('index'))

@app.route('/edit/<int:note_id>', methods=['GET', 'POST'])
def edit_note(note_id):
    note = Note.query.get(note_id)
    if request.method == 'POST':
        note_title = request.form['title']
        note_content = request.form['content']
        tags = request.form['tags']
        save_note_to_file(note.filename, note_content, tags, update=True)
        note.tags = tags
        db.session.commit()
        return redirect(url_for('index'))
    title, tags, content, _ = load_note_from_file(note.filename)
    return render_template('note.html', note=note, content=content)

@app.route('/search', methods=['GET'])
def search_notes():
    query = request.args.get('q', '')
    notes = Note.query.all()
    if query:
        notes = [note for note in notes if query.lower() in note.filename.lower()]
    return render_template('index.html', notes=notes, tags=[])

if __name__ == '__main__':
    app.run(debug=True)
